//
//  HSLoginViewController.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/9/29.
//  Copyright © 2016年 黄华强. All rights reserved.
//

import UIKit
import SVProgressHUD

class HSLoginViewController: UIViewController {
    
    lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)//菊花为
    
    
    //登录按钮属性
    @IBOutlet weak var loginButton: UIButton!
    //密码输入框
    @IBOutlet weak var loginPassWordTF: UITextField!
    //用户名输入框
    @IBOutlet weak var loginAccountTF: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        //添加活动指示器
        activity.center = view.center
        activity.color = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)
        view.addSubview(activity)
        
    }
    
    //数据请求
    func downloadData() {
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    @IBAction func loginBtnClicked(_ sender: UIButton) {
        //先判断用户是否已经设置IP地址
        if baseURLString == nil || baseURLString! == "zao/interface/" {
            //弹窗
            SVProgressHUD.showInfo(withStatus: "请先设置学校IP地址")
            return
        }
        
        guard let acc = loginAccountTF.text, acc != "" else {
            SVProgressHUD.showInfo(withStatus: "账号不能为空")
            return
        }
        
        guard let pass = loginPassWordTF.text, pass != "" else {
            SVProgressHUD.showInfo(withStatus: "密码不能为空")
            return
        }
        
        activity.startAnimating()
        
        let urlStr = (baseURLString ?? "") + "ZH-schoolname-S-login"
        //参数字典
        let param = ["code":acc,"password":pass]
        HSNetWorkTools.shared.downloadData(url: urlStr, parameters: param) {[weak self] (data, error) in
            self?.activity.stopAnimating()
            
            if error != nil {
                SVProgressHUD.showInfo(withStatus: "网络请求失败,请检查IP地址")
                //弹窗
                return
            }
            //获得返回数据
            guard let dict = data as? NSDictionary else {
                return
            }
            print(dict)
            //将类型转换为Int
            switch dict["result"] as! Int {
            case 0:
                //获得保存路径
                dict.write(toFile: saveUserInfoPath, atomically: true)
                
                UIApplication.shared.keyWindow?.rootViewController = HSDrawerViewController()
                UserDefaults.standard.set(true, forKey: isLogin)
            //跳转到下一个页面
            case 1:
                SVProgressHUD.showInfo(withStatus: "账号或密码错误")
                print("账号或密码错误")
            default:
                break
            }
        }
        
    }
    
    ///设置UI
    fileprivate func setupUI() {
        loginButton.layer.cornerRadius = 5
        //设置边框
        loginButton.layer.borderColor = UIColor.gray.cgColor
        loginButton.layer.borderWidth = 1
        
        loginAccountTF.leftView = setupLeftView(imageName: "icon_user")
        loginAccountTF.leftViewMode = .always
        
        loginPassWordTF.leftView = setupLeftView(imageName: "icon_password")
        loginPassWordTF.leftViewMode = .always
        
    }
    
    fileprivate func setupLeftView(imageName: String) -> UIView {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        let firstV = UIImageView(image: UIImage(named: imageName))
        
        firstV.center = CGPoint(x: firstV.bounds.width/2 + 8, y: 22)
        bgView.addSubview(firstV)
        
        let twoV = UIImageView(image: UIImage(named: "line_edit_sep"))
        twoV.center = CGPoint(x: firstV.frame.maxX + twoV.bounds.width/2 + 5, y: 22)
        bgView.addSubview(twoV)
        
        return bgView
    }
    
    ///调整状态栏模式
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    @IBAction func loginSetingBtnClicked(_ sender: UIButton) {
        let alertVC = UIAlertController(title: "请输入学校服务器的IP地址", message: nil, preferredStyle: .alert)
        alertVC.addTextField { (textF) in
            textF.placeholder = "IP地址"
            let saveIP = UserDefaults.standard.value(forKey: hhq_ipKey)
            textF.text = saveIP as? String
            
            textF.borderStyle = .none
            textF.textAlignment = .center
        }
        alertVC.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            let IPText = alertVC.textFields?[0].text
            UserDefaults.standard.setValue(IPText, forKey: hhq_ipKey)
        }))
        
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        
        present(alertVC, animated: true, completion: nil)
    }
    
}

extension HSLoginViewController {
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
}



